package com.niodata.dp.api.server;

import com.niodata.dp.log.LogUtil;
import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class BaseController {

  private static final Logger logger = Logger.getLogger(BaseController.class);

  @ExceptionHandler
  @ResponseBody
  public Map exceptionHandle(Exception ex, HttpServletResponse response) {
    LogUtil.logStackTrace(logger, ex);
    Map errorInfo = new HashMap();
    if (response.getStatus() == 200 || response.getStatus() == 0) {
      response.setStatus(500);
    }
    String msg = ex.getMessage();
    if (msg != null) {
      errorInfo.put("error", ex.getMessage());
    } else {
      errorInfo.put("error", "internal error");
    }
    return errorInfo;
  }

  public void setProcessedHeader(HttpServletResponse response) {
    response.setHeader("X-Processed", "true");
  }
}
